package com.pm.controller.task;

import com.github.pagehelper.PageInfo;
import com.pm.common.Pages;
import com.pm.common.Response;
import com.pm.common.annotation.CurrentUser;
import com.pm.common.annotation.MyLog;
import com.pm.common.annotation.UserLoginToken;
import com.pm.common.exception.CommonException;
import com.pm.common.exception.ExpCodeState;
import com.pm.entity.po.security.User;
import com.pm.entity.po.task.Task;
import com.pm.entity.po.task.TaskCollectionCheckLog;
import com.pm.entity.po.task.TaskCompletionDegree;
import com.pm.entity.po.task.TaskSubtasks;
import com.pm.entity.vo.DegreeVO;
import com.pm.mapper.log.DepartmentScoreCheckLogMapper;
import com.pm.mapper.log.TaskSubtasksCheckLogMapper;
import com.pm.mapper.task.TaskCollectionCheckLogMapper;
import com.pm.mapper.task.TaskSubtasksMapper;
import com.pm.service.task.TaskCollectionCheckLogService;
import com.pm.service.task.TaskService;
import com.pm.service.task.TaskSubtasksService;
import com.pm.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Api(tags = "任务管理")
@UserLoginToken
@RestController
@RequestMapping("/task")
public class TaskController {
    @Autowired
    TaskService taskService;
    @Autowired
    TaskCollectionCheckLogService taskCollectionCheckLogService;
    @Autowired
    TaskSubtasksService taskSubtasksService;
    @Autowired
    TaskCollectionCheckLogMapper taskCollectionCheckLogMapper;
    @Autowired
    TaskSubtasksCheckLogMapper taskSubtasksCheckLogMapper;
    @Autowired
    DepartmentScoreCheckLogMapper departmentScoreCheckLogMapper;
    @Autowired
    TaskSubtasksMapper taskSubtasksMapper;

    @ApiOperation("新增接口")
    @PostMapping("/add")
    @ResponseBody
    @MyLog(value = "新增任务信息")
    public Response<Integer> add(Task task) {
        Response<Integer> response = null;
        Integer result = taskService.add(task);
        if (result > 0) {
            response = new Response<>(ExpCodeState.add_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.add_data_failed);
        }
        return response;
    }

    @ApiOperation("提交审核")
    @PostMapping("/auditing")
    @ResponseBody
    @MyLog(value = "任务提交审核")
    @Transactional(rollbackFor = CommonException.class)
    public Response<Integer> auditing(Task task, @CurrentUser User user) {
        Response<Integer> response = null;
        task.setCheckStatus(1);
        // 修改状态
        Integer result = taskService.update(task);
        TaskCollectionCheckLog taskCollectionCheckLog = new TaskCollectionCheckLog();
        taskCollectionCheckLog.setStatus(0);
        taskCollectionCheckLog.setRead(0);
        taskCollectionCheckLog.setTaskId(task.getId());
        // 添加申请人申请时间
        taskCollectionCheckLog.setApplicat(user.getUserId());
        taskCollectionCheckLogService.add(taskCollectionCheckLog);
        if (result > 0) {
            response = new Response<>(ExpCodeState.add_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.add_data_failed);
        }
        return response;
    }

    @ApiOperation("更新接口")
    @PostMapping("/update")
    @ResponseBody
    @MyLog(value = "编辑任务信息")
    public Response<Integer> update(Task task) {
        Response<Integer> response = null;
        Integer result = taskService.update(task);
        if (result > 0) {
            response = new Response<>(ExpCodeState.update_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.update_data_failed);
        }
        return response;
    }

    @ApiOperation("删除接口")
    @PostMapping("/remove")
    @ResponseBody
    @MyLog(value = "删除任务信息")
    @Transactional(rollbackFor = CommonException.class)
    public Response<Integer> remove(Task task) {
        Response<Integer> response = null;
        Integer taskSubtaskNum = taskSubtasksService.getTaskSubtaskNum(task.getId());
        // 有子任务，不允许删除
        if (taskSubtaskNum > 0) {
            return new Response<>(ExpCodeState.remove_task_failed);
        }
        Integer result = taskService.remove(task);
        if (result > 0) {
            response = new Response<>(ExpCodeState.remove_data_success, result);
        } else {
            response = new Response<>(ExpCodeState.remove_data_failed);
        }
        return response;
    }

    @ApiOperation("单个对象查询接口")
    @PostMapping("/load")
    @ResponseBody
    public Response<Task> load(Task task) {
        Response<Task> response = null;
        Task result = taskService.load(task);
        response = new Response<Task>(ExpCodeState.query_data_success, result);
        return response;
    }

    @ApiOperation("全部列表查询接口(不带数据权限)")
    @PostMapping("/getAllList")
    @ResponseBody
    public Response<List<Task>> getAllList(Task task, @CurrentUser User user) {
        TaskSubtasks taskSubtasks = new TaskSubtasks();
        task.setDepartmentId(user.getDepartmentId());
        task.setYear(DateUtil.getYear(new Date()));
        //task.setId(user.getTaskId());
        List<Task> result = taskService.getList(task);
        // 组装返回的list集合数据
        makeUpResultList(result);
        Response<List<Task>> res = new Response<List<Task>>(ExpCodeState.query_data_success, result);
        return res;
    }

    @ApiOperation("全部列表查询接口(带数据权限)")
    @PostMapping("/getList")
    @ResponseBody
    public Response<List<Task>> getList(Task task, @CurrentUser User user) {
        TaskSubtasks taskSubtasks = new TaskSubtasks();
        task.setDepartmentId(user.getDepartmentId());
        task.setYear(DateUtil.getYear(new Date()));
        task.setIds(user.getTaskId());
        //task.setName("测试");
        List<Task> result = taskService.getList(task);
        // 组装返回的list集合数据
        makeUpResultList(result);
        Response<List<Task>> res = new Response<>(ExpCodeState.query_data_success, result);
        return res;
    }

    /**
     * 组装返回的list集合数据
     * @param result
     */
    private void makeUpResultList(List<Task> result) {
        TaskSubtasks taskSubtasks;
        for (Task resultOne : result) {
            // 状态
            taskSubtasks = taskSubtasksMapper.getListOne(resultOne.getId());
            boolean reject = true;
            if (resultOne.getId() == 55) {
                System.out.println(resultOne.getId());
            }
            if (taskSubtasks == null) {
                resultOne.setOneQuarterDegreeStatus(null);
                resultOne.setTwoQuarterDegreeStatus(null);
                resultOne.setThreeQuarterDegreeStatus(null);
                resultOne.setAllDegreeStatus(null);
                resultOne.setReject(true);
            } else {
                resultOne.setOneQuarterDegreeStatus(taskSubtasks.getOneQuarterDegreeStatus());
                resultOne.setTwoQuarterDegreeStatus(taskSubtasks.getTwoQuarterDegreeStatus());
                resultOne.setThreeQuarterDegreeStatus(taskSubtasks.getThreeQuarterDegreeStatus());
                resultOne.setAllDegreeStatus(taskSubtasks.getAllDegreeStatus());
                // 如果四个季度中有任意一个季度已经开始走任务进度审核流程，则不允许目标任务再驳回
                reject = taskSubtasks.getOneQuarterDegreeStatus() != 0 || taskSubtasks.getTwoQuarterDegreeStatus() != 0
                        || taskSubtasks.getThreeQuarterDegreeStatus() != 0 || taskSubtasks.getAllDegreeStatus() != 0;
                if (reject) {
                    resultOne.setReject(false);
                } else {
                    resultOne.setReject(true);
                }
            }
            // 如果是 待审核 并且 没有开始走进度审核流程 的状态，则驳回状态设为true
            if (1 == resultOne.getCheckStatus() && !reject) {
                resultOne.setReject(true);
            } else if (-1 == resultOne.getCheckStatus() || 0 == resultOne.getCheckStatus()) {
                resultOne.setReject(false);
            }

            // 采集
            resultOne.setApplicatName(taskCollectionCheckLogMapper.getApplicatName(resultOne.getId()));
            resultOne.setAuditorName(taskCollectionCheckLogMapper.getAuditorName(resultOne.getId()));
            //审核
            resultOne.setTscApplicatName(taskSubtasksCheckLogMapper.getTscApplicatName(resultOne.getId()));
            resultOne.setTscAuditorName(taskSubtasksCheckLogMapper.getscAuditorName(resultOne.getId()));
            //打分审核记录表
            resultOne.setDsApplicatName(departmentScoreCheckLogMapper.getDsApplicatName(resultOne.getId()));
            resultOne.setDsAuditorName(departmentScoreCheckLogMapper.getDsAuditorName(resultOne.getId()));
            for (Task resultChildren : resultOne.getChildren()) {
                taskSubtasks = taskSubtasksMapper.getListOne(resultChildren.getId());
                if (taskSubtasks == null) {
                    resultChildren.setOneQuarterDegreeStatus(null);
                    resultChildren.setTwoQuarterDegreeStatus(null);
                    resultChildren.setThreeQuarterDegreeStatus(null);
                    resultChildren.setAllDegreeStatus(null);
                } else {
                    resultChildren.setOneQuarterDegreeStatus(taskSubtasks.getOneQuarterDegreeStatus());
                    resultChildren.setTwoQuarterDegreeStatus(taskSubtasks.getTwoQuarterDegreeStatus());
                    resultChildren.setThreeQuarterDegreeStatus(taskSubtasks.getThreeQuarterDegreeStatus());
                    resultChildren.setAllDegreeStatus(taskSubtasks.getAllDegreeStatus());
                }
                // 采集
                resultChildren.setApplicatName(taskCollectionCheckLogMapper.getApplicatName(resultChildren.getId()));
                resultChildren.setAuditorName(taskCollectionCheckLogMapper.getAuditorName(resultChildren.getId()));
                //审核
                resultChildren.setTscApplicatName(taskSubtasksCheckLogMapper.getTscApplicatName(resultChildren.getId()));
                resultChildren.setTscAuditorName(taskSubtasksCheckLogMapper.getscAuditorName(resultChildren.getId()));
                //打分审核记录表
                resultChildren.setDsApplicatName(departmentScoreCheckLogMapper.getDsApplicatName(resultChildren.getId()));
                resultChildren.setDsAuditorName(departmentScoreCheckLogMapper.getDsAuditorName(resultChildren.getId()));
            }
        }
        setDegree(result);
    }

    @ApiOperation("分页查询接口")
    @PostMapping("/getListByPage/{pageNum}/{pageSize}")
    @ResponseBody
    @MyLog(value = "查询任务信息")
    public Response<PageInfo<Task>> getList(Task task, Pages page) {
        PageInfo<Task> result = taskService.getListByPage(task, page);
        Response<PageInfo<Task>> res = new Response<PageInfo<Task>>(ExpCodeState.query_data_success, result);
        return res;
    }

    private void setDegree(List<Task> result) {
        for (Task t : result) {
            DegreeVO degree = new DegreeVO();
            if (t == null) {
                // t为null时，跳过循环
                continue;
            }
            for (TaskCompletionDegree de : t.getCompletionDegrees()) {
                if (de == null || de.getTime() == null) {
                    // de为null时，跳过循环
                    continue;
                }
                switch (de.getTime()) {
                    case 1:
                        if (de.getType() == 1) {
                            degree.setQuarter1(de.getDegree());
                        } else {
                            degree.setMoth1(de.getDegree());
                        }
                        break;
                    case 2:
                        if (de.getType() == 1) {
                            degree.setQuarter2(de.getDegree());
                        } else {
                            degree.setMoth2(de.getDegree());
                        }
                        break;
                    case 3:
                        if (de.getType() == 1) {
                            degree.setQuarter3(de.getDegree());
                        } else {
                            degree.setMoth3(de.getDegree());
                        }
                        break;
                    case 4:
                        if (de.getType() == 1) {
                            degree.setQuarter4(de.getDegree());
                        } else {
                            degree.setMoth4(de.getDegree());
                        }
                        break;
                    case 5:
                        degree.setMoth5(de.getDegree());
                        break;
                    case 6:
                        degree.setMoth6(de.getDegree());
                        break;
                    case 7:
                        degree.setMoth7(de.getDegree());
                        break;
                    case 8:
                        degree.setMoth8(de.getDegree());
                        break;
                    case 9:
                        degree.setMoth9(de.getDegree());
                        break;
                    case 10:
                        degree.setMoth10(de.getDegree());
                        break;
                    case 11:
                        degree.setMoth11(de.getDegree());
                        break;
                    case 12:
                        degree.setMoth12(de.getDegree());
                        break;
                }
            }
            t.setDegree(degree);
            if (null != t.getChildren() && !t.getChildren().isEmpty()) {
                setDegree(t.getChildren());
            }
        }
    }

}
